package com.xjtu.util;


import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
public class NetworkUtil {
    public static void configureLink(String containerName, String bandwidth, String delay) throws Exception {
        String command = String.format(
                "docker exec %s tc qdisc add dev eth0 root tbf rate %s burst 32kbit latency %s",
                containerName, bandwidth, delay
        );
        executeCommand(command);
    }
    public static void executeAttack(String containerId, int attackType, String targetIp) throws Exception {
        String attackCommand = attackMapper(attackType, targetIp);
        // 在攻击容器中执行攻击命令
        String command = String.format("docker exec %s %s", containerId, attackCommand);
        executeCommand(command);
    }
    private static String attackMapper(int attackType , String targetIp) {
        /*
        docker run --rm attacker-image:latest python attack_simulator.py ddos 192.168.1.100 60
        docker run --rm attacker-image:latest python attack_simulator.py dns_poisoning 192.168.1.100 1.2.3.4
        docker run --rm attacker-image:latest python attack_simulator.py arp_spoofing 192.168.1.100 192.168.1.1
        docker run --rm attacker-image:latest python attack_simulator.py syn_flood 192.168.1.100 80
        */
        switch (attackType) {
            case 1:
                return "python attack_simulator.py ddos " + targetIp + " 60";
            case 2:
                return "python attack_simulator.py dns_poisoning " + targetIp + " 1.2.3.4";
            case 3:
                return "python attack_simulator.py arp_spoofing " + targetIp + " 192.168.1.1";
            case 4:
                return "python attack_simulator.py syn_flood " + targetIp + " 80";
            default:
                return "";
        }

    }
    private static void executeCommand(String command) throws Exception {
        Process process = Runtime.getRuntime().exec(command);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("executeInfo: {}",line);
            }
        }
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("Command execution failed: " + command);
        }
    }

    /**
     * 获取容器的流量信息
     * @param containerId 容器 ID
     * @return 流量信息
     * @throws Exception
     */
    public static String getTrafficInfo(String containerId) throws Exception {

        String command = "docker exec " + containerId + " ifconfig eth0";
        Process process = Runtime.getRuntime().exec(command);

        // 读取命令输出
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            long rxBytes = 0; // 接收字节数
            long txBytes = 0; // 发送字节数

            while ((line = reader.readLine()) != null) {
                // 提取 RX bytes 和 TX bytes 的值
                if (line.contains("RX bytes")) {
                    String[] parts = line.split(" ");
                    for (String part : parts) {
                        if (part.startsWith("bytes:")) {
                            rxBytes = Long.parseLong(part.split(":")[1]);
                        }
                    }
                } else if (line.contains("TX bytes")) {
                    String[] parts = line.split(" ");
                    for (String part : parts) {
                        if (part.startsWith("bytes:")) {
                            txBytes = Long.parseLong(part.split(":")[1]);
                        }
                    }
                }
            }

            // 返回提取的流量信息
            return String.format("Container ID: %s, RX bytes: %d, TX bytes: %d", containerId, rxBytes, txBytes);
        }
        /*
            RX bytes（接收字节数）：
                反映服务器接收到的流量，DDoS 攻击通常会导致该值显著增加。
            TX bytes（发送字节数）：
                反映服务器响应的流量，可能会因为攻击而增加（如 HTTP 响应）或减少（如服务器被压垮）。
                通过监控这两个指标，可以直观地观察攻击对服务器网络的影响。
         */
    }
}
